package com.feicheng.service.a;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.task.Cache;
import com.feicheng.common.util.DateUtils;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.*;
import com.feicheng.persistence.mapper.*;
import com.feicheng.persistence.mapper.ClientMapper;
import com.feicheng.persistence.model.KcWithJlModel;
import com.feicheng.persistence.model.SkjlModel;
import com.feicheng.persistence.service.*;
import com.feicheng.service.AsyncService;
import com.feicheng.wxapi.pay.WxAppPayBean;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class FKcService {

    @Autowired
    IAkechengService kechengService;

    @Autowired
    IAkechengitemService kechengitemService;

    @Autowired
    IAkechenglxService kechenglxService;

    @Autowired
    IAstoreService storeservice;

    @Autowired
    IAjiaolianService ajiaolianService;

    @Autowired
    IAmdjlService amdjlService;

    @Autowired
    IAdzService adzService;

    @Autowired
    IAroomService aroomService;

    @Autowired
    IAclientbmService clientbmService;

    @Autowired
    IClientService clientService;

    @Autowired
    IAkechengskjlService akechengskjlService;

    @Autowired
    IAkechengitemService akechengitemService;

    @Autowired
    IAmountService amountService;

    @Autowired
    IAroomyyjlService yyjlService;

    @Autowired
    IAroomyyjlitemService yyjlitemService;

    @Autowired
    IAroomhourlypricesService aroomhourlypricesService;

    @Autowired
    IAhyjlService hyjlService;

    @Autowired
    IAfxjlService fxjlService;

    @Autowired
    WxAppPayBean wxAppPayBean;

    @Autowired
    AsyncService asyncService;

    @Autowired
    Cache cache;

    private String appid;

    @PostConstruct
    private void init() {
        Asetting asetting = cache.getObject("Asetting", Asetting.class);
        appid = asetting.getJappid();
    }

    @Transactional
    public synchronized void kaishiKc() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nowAfter3H = now.plusHours(3);

        AkechengMapper akechengMapper = (AkechengMapper) kechengService.getBaseMapper();
        QueryWrapper<Akecheng> qw = new QueryWrapper<>();
        qw.eq("zt", "B");
        qw.le("fdt", nowAfter3H.format(Constant.yyyyMMddHHmmss));
        List<JSONObject> kcs = akechengMapper.getKcWithFtLt(qw);
        if (null != kcs && kcs.size() > 0) {
            kcs.forEach(obj -> {

                String kcid = obj.getString("kcid");
                Akecheng akecheng = new Akecheng();
                akecheng.setKcid(kcid);
                akecheng.setZxrs(obj.getInteger("zxrs"));
                akecheng.setZt(obj.getString("B"));

                QueryWrapper<Aclientbm> qwbm = new QueryWrapper<>();
                qwbm.eq("kcid", kcid);
                qwbm.eq("stu", "B");
                List<Aclientbm> aclientbms = clientbmService.list(qwbm);


                if (akecheng.getZxrs() > aclientbms.size()) {
                    this.cancelKc(akecheng);
                    return;
                }

                akecheng.setZt("D");
                kechengService.updateById(akecheng);

                if (null != aclientbms && aclientbms.size() > 0) {
                    aclientbms.forEach(bm -> {
                        bm.setStu("S");
                        bm.setCt(now);
                        clientbmService.updateById(bm);
                    });
                }

                qwbm.clear();
                qwbm.eq("kcid", kcid);
                qwbm.eq("stu", "P");
                aclientbms = clientbmService.list(qwbm);

                if (null != aclientbms && aclientbms.size() > 0) {
                    aclientbms.forEach(bm -> {
                        if (bm.getSort() > 0) {
                            bm.setStu("C");
                            bm.setCt(now);
                            clientbmService.updateById(bm);
                            Client client = clientService.getById(bm.getClientid());
                            Amount xyAmount = amountService.getById(client.getOpenid());
                            xyAmount.setAmount(xyAmount.getAmount().intValue() + bm.getSjzfje() + bm.getYezfje());
                            amountService.updateById(xyAmount);

                            QueryWrapper<Akechengskjl> skjlqw = new QueryWrapper<>();
                            skjlqw.in("bmid", bm.getBmid());
                            List<Akechengskjl> skjls = akechengskjlService.list(skjlqw);
                            skjls.forEach(skjl -> {
                                if (StringUtils.hasLength(skjl.getHyjlid())) {
                                    Ahyjl ahyjl = hyjlService.getById(skjl.getHyjlid());
                                    ahyjl.setSycs(ahyjl.getSycs() + 1);
                                    hyjlService.updateById(ahyjl);
                                }
                            });
                            akechengskjlService.remove(skjlqw);

                            if (StringUtils.hasLength(bm.getFxjlid())) {
                                fxjlService.removeById(bm.getFxjlid());
                            }

                        }
                    });
                }



            });
        }
    }

    @Transactional
    public synchronized void jiesuKc() {
        LocalDateTime now = LocalDateTime.now();

        AkechengMapper akechengMapper = (AkechengMapper) kechengService.getBaseMapper();
        QueryWrapper<Akecheng> qw = new QueryWrapper<>();
        qw.eq("zt", "D");
        qw.le("ldt", now.format(Constant.yyyyMMddHHmmss));
        List<JSONObject> kcs = akechengMapper.getKcWithFtLt(qw);
        if (null != kcs && kcs.size() > 0) {
            kcs.forEach(obj -> {
                String kcid = obj.getString("kcid");
                Akecheng akecheng = new Akecheng();
                akecheng.setKcid(kcid);
                akecheng.setZt("F");
                kechengService.updateById(akecheng);

                QueryWrapper<Aclientbm> qwbm = new QueryWrapper<>();
                qwbm.eq("kcid", kcid);
                qwbm.eq("stu", "S");
                List<Aclientbm> aclientbms = clientbmService.list(qwbm);

                if (null != aclientbms && aclientbms.size() > 0) {
                    aclientbms.forEach(bm -> {
                        bm.setStu("F");
                        bm.setCt(now);
                        clientbmService.updateById(bm);
                    });
                }
            });
        }
    }



    /**
     * 课程分页查询 老蔡
     * @param param
     * @return
     */
    public JSONObject getKcByPage(JSONObject param) {
        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<>(current, size);


        QueryWrapper<JSONObject> qw = new QueryWrapper<>();
        String kcname = param.getString("kcname");
        if (StringUtils.hasLength(kcname)) {
            qw.like("akecheng.kcname", kcname);
        }

        String kclxid = param.getString("kclxid");
        if (StringUtils.hasLength(kclxid)) {
            qw.eq("akecheng.kclxid", kclxid);
        }

        Integer bx = param.getInteger("bx");
        if (null != bx) {
            if (bx == 1) {
                qw.eq("akecheng.zdrs", bx);
            } else if (bx == 6) {
                qw.gt("akecheng.zdrs", 1);
                qw.le("akecheng.zdrs", bx);
            } else if (bx == 7) {
                qw.ge("akecheng.zdrs", bx);
            }
        }

        String sd = param.getString("sd");
        if (StringUtils.hasLength(sd)) {
            qw.ge("akecheng.st", sd);
        }

        String ed = param.getString("ed");
        if (StringUtils.hasLength(ed)) {
            qw.le("akecheng.et", ed);
        }

        String zt = param.getString("zt");
        if (StringUtils.hasLength(zt)) {
            qw.eq("akecheng.zt", zt);
        }

        String astoreid = param.getString("astoreid");
        if (StringUtils.hasLength(astoreid)) {
            QueryWrapper<Akechengitem> kcItemqw = new QueryWrapper<>();
            kcItemqw.select("DISTINCT kcid").eq("storeid", astoreid);
            JSONArray kcids = new JSONArray();
            akechengitemService.getBaseMapper().selectList(kcItemqw, item -> {
                kcids.add(item.getResultObject().getKcid());
            });
            param.put("kcids", kcids);
        }

        String aroomid = param.getString("aroomid");
        if (StringUtils.hasLength(aroomid)) {
            QueryWrapper<Akechengitem> kcItemqw = new QueryWrapper<>();
            kcItemqw.select("DISTINCT kcid").eq("roomid", aroomid);
            JSONArray kcids = new JSONArray();
            akechengitemService.getBaseMapper().selectList(kcItemqw, item -> {
                kcids.add(item.getResultObject().getKcid());
            });
            param.put("kcids", kcids);
        }

        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("akecheng.jlid", jlid);
        }

        String mdjlid = param.getString("mdjlid");
        if (StringUtils.hasLength(mdjlid)) {
            qw.eq("akecheng.mdjlid", mdjlid);
        }

        String mdid = param.getString("mdid");
        if (StringUtils.hasLength(mdid)) {
            qw.eq("akecheng.storeid", mdid);
        }

        List<String> kcids = param.getObject("kcids", new TypeReference<List<String>>() {});
        if (null != kcids && kcids.size() > 0) {
            qw.in("akecheng.kcid", kcids);
        }

        AkechengMapper akechengMapper = (AkechengMapper) kechengService.getBaseMapper();
        page = akechengMapper.getKcWithJlByPage(page, qw);

        param.put("akechengs", page);
        return param;
    }


    @Transactional
    public JSONObject kaike(JSONObject param) {

        Aroomyyjl aroomyyjl = param.getObject("aroomyyjl", Aroomyyjl.class);
        List<Aroomyyjlitem> aroomyyjlitems = param.getObject("aroomyyjlitems", new TypeReference<List<Aroomyyjlitem>>(){});
        Akecheng kecheng = param.getObject("akecheng", Akecheng.class);
        List<Akechengitem> akechengitems = param.getObject("akechengitems", new TypeReference<List<Akechengitem>>(){});
        Ajiaolian jiaolian = ajiaolianService.getById(aroomyyjl.getJlid());

        aroomyyjl.setRmorderid(StringGenerator.getID("YYJL"));
        aroomyyjl.setCt(LocalDateTime.now());
        aroomyyjl.setPflg(false);
        aroomyyjl.setTflg("P");

        List<String> itemids = new ArrayList<>();
        Integer amount = 0;
        for (Aroomyyjlitem aroomyyjlitem : aroomyyjlitems) {
            String cdStr = DateUtils.dateToString("yyyyMMdd", aroomyyjlitem.getCd());
            Aroomyyjlitem item = yyjlitemService.getById(aroomyyjlitem.getItemid());
            Aroomhourlyprices aroomhourlyprices = aroomhourlypricesService.getById(aroomyyjlitem.getHid());
            aroomyyjlitem.setHp(JSONObject.toJSONString(aroomhourlyprices));
            if (null != item) {
                throw new SystemException("当前预约时间段有冲突，请重新选择。日期：【"+cdStr+"】|时段：【"+aroomyyjlitem.getSt()+"-"+aroomyyjlitem.getEt()+"】");
            }
            itemids.add(aroomyyjlitem.getItemid());
            aroomyyjlitem.setRmorderid(aroomyyjl.getRmorderid());
            amount += aroomyyjlitem.getPrice();
        }
        aroomyyjl.setAmont(amount);
        aroomyyjl.setSfje(amount);
        aroomyyjl.setYezfje(0);

        Amount amountJl = amountService.getById(jiaolian.getOpenid());
        if (amountJl.getAmount() >= amount) {
            aroomyyjl.setAmont(amount);
            aroomyyjl.setSfje(0);
            aroomyyjl.setYezfje(amount);
            aroomyyjl.setPflg(true);

            amountJl.setAmount(amountJl.getAmount() - amount);
            amountService.updateById(amountJl);
        } else {
            aroomyyjl.setAmont(amount);
            aroomyyjl.setSfje(amount - amountJl.getAmount());
            aroomyyjl.setYezfje(amountJl.getAmount());

            amountJl.setAmount(0);
            amountService.updateById(amountJl);
            PrepayWithRequestPaymentResponse prepayData =
                    wxAppPayBean.jsapi(
                            aroomyyjl.getRmorderid(),
                            "预约订单",
                            "/notice-url/"+aroomyyjl.getRmorderid(),
                            aroomyyjl.getSfje(),
                            jiaolian.getOpenid(),
                            "",
                            appid
                    );
            String prepayId = prepayData.getPackageVal().split("=")[1];
            aroomyyjl.setPrepaydata(JSONObject.toJSONString(prepayData));
            aroomyyjl.setPrepayid(prepayId);
        }


        kecheng.setKcid(StringGenerator.getID("KC"));
        kecheng.setYbrs(0);
        for (Akechengitem akechengitem : akechengitems) {
            akechengitem.setKcid(kecheng.getKcid());
            if (null == kecheng.getSt()) {
                kecheng.setSt(akechengitem.getDt());
            } else {
                if (kecheng.getSt().isAfter(akechengitem.getDt())) {
                    kecheng.setSt(akechengitem.getDt());
                }
            }

            if (null == kecheng.getEt()) {
                kecheng.setEt(akechengitem.getDt());
            } else {
                if (kecheng.getEt().isBefore(akechengitem.getDt())) {
                    kecheng.setEt(akechengitem.getDt());
                }
            }
        }
        kecheng.setCs(akechengitems.size());

        yyjlService.save(aroomyyjl);
        yyjlitemService.saveBatch(aroomyyjlitems);
        kechengService.save(kecheng);
        kechengitemService.saveBatch(akechengitems);

        param.put("aroomyyjl", aroomyyjl);
        param.put("aroomyyjlitems", aroomyyjlitems);

        param.put("akecheng", kecheng);
        param.put("akechengitems", akechengitems);

        asyncService.runScheduler(() -> {
            synchronized (aroomyyjl.getRmorderid().intern()) {
                Aroomyyjl checkYyjl = yyjlService.getById(aroomyyjl.getRmorderid());
                if (!checkYyjl.getPflg()) {
                    yyjlitemService.removeByIds(itemids);
                    checkYyjl.setTflg("C");
                    yyjlService.updateById(checkYyjl);
                    kecheng.setZt("C");
                    kechengService.updateById(kecheng);
                    return "未支付，预约取消";
                }
                return "已支付，预约成功";
            }

        }, 2, "预约记录支付核减：【"+aroomyyjl.getRmorderid()+"】");

        return param;
    }

    @Transactional
    public JSONObject mdjlkaike(JSONObject param) {

        Aroomyyjl aroomyyjl = param.getObject("aroomyyjl", Aroomyyjl.class);
        List<Aroomyyjlitem> aroomyyjlitems = param.getObject("aroomyyjlitems", new TypeReference<List<Aroomyyjlitem>>(){});
        Akecheng kecheng = param.getObject("akecheng", Akecheng.class);
        List<Akechengitem> akechengitems = param.getObject("akechengitems", new TypeReference<List<Akechengitem>>(){});
        Amdjl mdjl = amdjlService.getById(aroomyyjl.getMdjlid());

        aroomyyjl.setRmorderid(StringGenerator.getID("YYJLZY"));
        aroomyyjl.setCt(LocalDateTime.now());
        aroomyyjl.setPflg(false);
        aroomyyjl.setTflg("P");

        List<String> itemids = new ArrayList<>();
        Integer amount = 0;
        for (Aroomyyjlitem aroomyyjlitem : aroomyyjlitems) {
            String cdStr = DateUtils.dateToString("yyyyMMdd", aroomyyjlitem.getCd());
            Aroomyyjlitem item = yyjlitemService.getById(aroomyyjlitem.getItemid());
            Aroomhourlyprices aroomhourlyprices = aroomhourlypricesService.getById(aroomyyjlitem.getHid());
            aroomyyjlitem.setHp(JSONObject.toJSONString(aroomhourlyprices));
            if (null != item) {
                throw new SystemException("当前预约时间段有冲突，请重新选择。日期：【"+cdStr+"】|时段：【"+aroomyyjlitem.getSt()+"-"+aroomyyjlitem.getEt()+"】");
            }
            itemids.add(aroomyyjlitem.getItemid());
            aroomyyjlitem.setRmorderid(aroomyyjl.getRmorderid());
            amount += aroomyyjlitem.getPrice();
        }
        aroomyyjl.setAmont(amount);
        aroomyyjl.setSfje(amount);
        aroomyyjl.setYezfje(0);
        aroomyyjl.setPflg(true);

        kecheng.setKcid(StringGenerator.getID("KC"));
        kecheng.setYbrs(0);
        for (Akechengitem akechengitem : akechengitems) {
            akechengitem.setKcid(kecheng.getKcid());
            if (null == kecheng.getSt()) {
                kecheng.setSt(akechengitem.getDt());
            } else {
                if (kecheng.getSt().isAfter(akechengitem.getDt())) {
                    kecheng.setSt(akechengitem.getDt());
                }
            }

            if (null == kecheng.getEt()) {
                kecheng.setEt(akechengitem.getDt());
            } else {
                if (kecheng.getEt().isBefore(akechengitem.getDt())) {
                    kecheng.setEt(akechengitem.getDt());
                }
            }
        }
        kecheng.setCs(akechengitems.size());

        yyjlService.save(aroomyyjl);
        yyjlitemService.saveBatch(aroomyyjlitems);
        kechengService.save(kecheng);
        kechengitemService.saveBatch(akechengitems);

        param.put("aroomyyjl", aroomyyjl);
        param.put("aroomyyjlitems", aroomyyjlitems);

        param.put("akecheng", kecheng);
        param.put("akechengitems", akechengitems);

        return param;
    }

    /**
     * 新增课程 老蔡
     * @param param
     * @return
     */
    @Transactional
    public JSONObject newKc(JSONObject param) {
        Akecheng kecheng = param.getObject("akecheng", Akecheng.class);
        kecheng.setKcid(StringGenerator.getID("KC"));

        List<Akechengitem> akechengitems = param.getObject("akechengitems", new TypeReference<List<Akechengitem>>(){});
        for (Iterator<Akechengitem> it = akechengitems.iterator(); it.hasNext();) {
            Akechengitem akechengitem = it.next();
            akechengitem.setKcitemid(StringGenerator.getID("KCIT"));
            akechengitem.setKcid(kecheng.getKcid());

            if (null == kecheng.getSt()) {
                kecheng.setSt(akechengitem.getDt());
            } else {
                if (kecheng.getSt().isAfter(akechengitem.getDt())) {
                    kecheng.setSt(akechengitem.getDt());
                }
            }

            if (null == kecheng.getEt()) {
                kecheng.setEt(akechengitem.getDt());
            } else {
                if (kecheng.getEt().isBefore(akechengitem.getDt())) {
                    kecheng.setEt(akechengitem.getDt());
                }
            }

            Aroomyyjlitem yyitem = yyjlitemService.getById(akechengitem.getRmsyid());
            yyitem.setKcitemid(akechengitem.getKcitemid());
            yyjlitemService.updateById(yyitem);
        }
        kecheng.setCs(akechengitems.size());
        kechengService.save(kecheng);
        param.put("akecheng", kecheng);
        kechengitemService.saveBatch(akechengitems);
        param.put("akechengitems", akechengitems);
        return param;
    }

    private Akecheng cancelKc(Akecheng kecheng) {
        kecheng.setZt("C");
        kechengService.updateById(kecheng);

        QueryWrapper<Akechengitem> qwitems = new QueryWrapper<>();
        qwitems.eq("kcid", kecheng.getKcid());
        List<Akechengitem> items = akechengitemService.list(qwitems);
        items.forEach(item -> {
            Aroomyyjlitem yyitem = yyjlitemService.getById(item.getRmsyid());
            yyitem.setKcitemid("");
            yyjlitemService.updateById(yyitem);
        });


        QueryWrapper<Aclientbm> qwbm = new QueryWrapper<>();
        qwbm.eq("kcid", kecheng.getKcid());
        qwbm.and(q -> {
            q.or().eq("stu", "P");
            q.or().eq("stu", "B");
        });
        List<Aclientbm> aclientbms = clientbmService.list(qwbm);

        if (null != aclientbms && aclientbms.size() > 0) {
            aclientbms.forEach(bm -> {
                bm.setStu("C");
                bm.setCt(LocalDateTime.now());
                clientbmService.updateById(bm);
                Client client = clientService.getById(bm.getClientid());
                Amount xyAmount = amountService.getById(client.getOpenid());
                xyAmount.setAmount(xyAmount.getAmount().intValue() + bm.getSjzfje() + bm.getYezfje());
                amountService.updateById(xyAmount);


                if (StringUtils.hasLength(bm.getFxjlid())) {
                    fxjlService.removeById(bm.getFxjlid());
                }

                QueryWrapper<Akechengskjl> skjlqw = new QueryWrapper<>();
                skjlqw.in("bmid", bm.getBmid());
                if (bm.getSyhycs() > 0) {
                    List<Akechengskjl> skjls = akechengskjlService.list(skjlqw);
                    skjls.forEach(skjl -> {
                        if (StringUtils.hasLength(skjl.getHyjlid())) {
                            Ahyjl ahyjl = hyjlService.getById(skjl.getHyjlid());
                            ahyjl.setSycs(ahyjl.getSycs() + 1);
                            hyjlService.updateById(ahyjl);
                        }
                    });
                }
                akechengskjlService.remove(skjlqw);
            });
        }

        return kecheng;
    }



    @Transactional
    public JSONObject cancelKc(JSONObject param) {
        Akecheng kecheng = param.getObject("akecheng", Akecheng.class);

        synchronized (kecheng.getKcid().intern()) {
            kecheng = kechengService.getById(kecheng.getKcid());

            if (!"B".equals(kecheng.getZt())) {
                throw new SystemException("课程无法取消");
            }

            AkechengMapper akechengMapper = (AkechengMapper) kechengService.getBaseMapper();
            QueryWrapper<Akecheng> kcqw = new QueryWrapper<>();
            kcqw.eq("kcid", kecheng.getKcid());
            List<JSONObject> kcs = akechengMapper.getKcWithFtLt(kcqw);
            JSONObject kc = kcs.get(0);
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime nowAfter3H = now.plusHours(3L);
            String fdt = kc.getString("fdt");
            LocalDateTime fdtLocal = LocalDateTime.parse(fdt, Constant.yyyyMMddHHmmss);

            if (nowAfter3H.isAfter(fdtLocal)) {
                throw new SystemException("距开课时间已经不足3小时，无法取消");
            }

            kecheng = this.cancelKc(kecheng);

            param.put("kecheng", kecheng);
            return param;
        }
    }

    /**
     * 课程详细查询 斌哥
     * @param param
     * @return
     */
    public JSONObject getKc(JSONObject param) {
        String kcid = param.getString("kcid");
        if (!StringUtils.hasLength(kcid)) {
            throw new SystemException("课程id必须指定");
        }
        // 课程信息
        Akecheng akecheng = kechengService.getById(kcid);
        param.put("akecheng", akecheng);

        // 课程类型信息
        Akechenglx akechenglx = kechenglxService.getById(akecheng.getKclxid());
        param.put("akechenglx", akechenglx);

         //客户报名信息
        QueryWrapper<Aclientbm> qwBm = new QueryWrapper<>();
        qwBm.eq("kcid", akecheng.getKcid());
        List<Aclientbm> aclientbms = clientbmService.list(qwBm);
        param.put("aclientbms", aclientbms);

        //报名学员信息
        QueryWrapper<Client> qwClient = new QueryWrapper<>();
        qwClient.eq("aclientbm.kcid", akecheng.getKcid());
        AclientbmMapper bmMapper = (AclientbmMapper) clientbmService.getBaseMapper();
        List<JSONObject> clients = bmMapper.getBmWithJlKcByList(qwClient);
        param.put("clients", clients);

        // 教练信息
        if (StringUtils.hasLength(akecheng.getJlid())) {
            Ajiaolian jiaolian = ajiaolianService.getById(akecheng.getJlid());
            param.put("jiaolian", jiaolian);
        }

        // 门店教练信息
        if (StringUtils.hasLength(akecheng.getMdjlid())) {
            Amdjl amdjl = amdjlService.getById(akecheng.getMdjlid());
            param.put("amdjl", amdjl);
        }

        // 课程单节信息
        QueryWrapper<Akechengitem> itemqw = new QueryWrapper<>();
        itemqw.eq("kcid", akecheng.getKcid());
        itemqw.orderByAsc("akechengitem.dt", "akechengitem.st");
        //List<JSONObject> itemsJSON = new ArrayList<>();
        AkechengitemMapper akechengitemMapper = (AkechengitemMapper) kechengitemService.getBaseMapper();
        List<JSONObject> itemsJSON = akechengitemMapper.getRoomAndStoreWithKcItem(itemqw);
        param.put("kechengitems", itemsJSON);

        return param;
    }

    /**
     * 课程修改 老蔡
     * @param param
     * @return
     */
    public JSONObject updateKc(JSONObject param) {
        Akecheng akecheng = param.getObject("akecheng", Akecheng.class);
        kechengService.updateById(akecheng);
        param.put("akecheng", akecheng);
        return param;
    }



    /**
     * 取得课程类型树 老蔡
     * @return
     */
    public JSONObject getKclxTree() {
        JSONObject result = new JSONObject();
        List<Akechenglx> baseNodes = new ArrayList<>();
        List<Akechenglx> lxs = kechenglxService.list();

        JSONObject map = new JSONObject();
        cache.put("kclxs", map);
        for(Akechenglx lx : lxs) {
            lx.setSubs(new ArrayList<Akechenglx>());
            if (!StringUtils.hasLength(lx.getPid()) || "0".equals(lx.getPid())) {
                baseNodes.add(lx);
            }
            map.put(lx.getAkclxid(), lx);
        }

        for(Akechenglx lx : lxs) {
            if (!"0".equals(lx.getPid())) {
                Akechenglx plx = map.getObject(lx.getPid(), Akechenglx.class);
                plx.getSubs().add(lx);
            }
        }
        result.put("akechenglxs", baseNodes);
        return result;
    }


    public JSONObject getKclxList(JSONObject param) {
        List<Akechenglx> lxs = kechenglxService.list();
        param.put("lxs", lxs);
        return param;
    }

    /**
     * 新增课程类型  仕哥
     * @param param
     * @return
     */
    public JSONObject newKclx(JSONObject param) {
        // 从参数中提取课程类型信息
        Akechenglx akechenglx = param.getObject("akechenglx", Akechenglx.class);

        // 验证输入参数
        if (!StringUtils.hasLength(akechenglx.getLxname())) {
            throw new SystemException("类型名称不能为空");
        }
        akechenglx.setAkclxid(StringGenerator.getID("KCLX"));
        Akechenglx parent = kechenglxService.getById(akechenglx.getPid());
        akechenglx.setZs("【"+akechenglx.getPid()+"】,"+parent.getZs());
        kechenglxService.save(akechenglx);
        param.put("akechenglx", akechenglx);
        return param;
    }

    /**
     * 删除课程类型   教练课程类型  json保存  删除时需处理 老蔡
     * @param param
     * @return
     */
    public JSONObject deleteKclx(JSONObject param) {
        String kclxid = param.getString("kclxid");
        QueryWrapper<Akechenglx> qw = new QueryWrapper<>();
        qw.eq("pid", kclxid);
        long count = kechenglxService.count(qw);
        if (count > 0) {
            throw new SystemException("该分类有下级分类，无法删除");
        }
        kechenglxService.removeById(kclxid);
        return param;
    }


    /**
     * 上课记录分页查询  成哥
     * @param param
     * @return
     */
    public JSONObject getskjlsByPage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> qw = new QueryWrapper<>();
        String skjlid = param.getString("skjlid");
        if (StringUtils.hasLength(skjlid)) {
            qw.eq("akechengskjl.skjlid", skjlid);
        }

        String kcname = param.getString("kcname");
        if (StringUtils.hasLength(kcname)) {
            qw.like("akechengskjl.kcname", kcname);
        }

        AkechengskjlMapper akechengskjlMapper =
                (AkechengskjlMapper)akechengskjlService.getBaseMapper();
        page = akechengskjlMapper.getSkjlWithKcitemByPage(page, qw);

        param.put("skjls", page);

        return param;
    }



    /**
     * 上课记录详细查询 成哥
     * @param param
     * @return
     */
    public JSONObject getSkjl(JSONObject param) {

        String skjlid = param.getString("skjlid");
        if (!StringUtils.hasLength(skjlid)) {
            throw new SystemException("上课记录ID必须指定");
        }

        //上课记录表
        Akechengskjl akechengskjl = akechengskjlService.getById(skjlid);
        param.put("akechengskjl", akechengskjl);
        //客户表
        Client client = clientService.getById(akechengskjl.getClientid());
        param.put("client", client);
        //课程单节表
        Akechengitem Akechengitem = akechengitemService.getById(akechengskjl.getKcitemid());
        param.put("Akechengitem", Akechengitem);
        //课程表
        Akecheng akecheng = kechengService.getById(Akechengitem.getKcid());
        param.put("akecheng", akecheng);
        //教练表
        Ajiaolian ajiaolian = ajiaolianService.getById(akecheng.getJlid());
        param.put("ajiaolian", ajiaolian);

        return param;
    }

    public JSONObject getKcitemWithAllByPage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        Page<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> qw = new QueryWrapper<>();

        String storeid = param.getString("storeid");
        if (StringUtils.hasLength(storeid)) {
            qw.eq("item.storeid", storeid);
        }

        String roomid = param.getString("roomid");
        if (StringUtils.hasLength(roomid)) {
            qw.eq("item.roomid", roomid);
        }

        String dt = param.getString("dt");
        if (StringUtils.hasLength(dt)) {
            qw.eq("item.dt", dt);
        }

        String st = param.getString("st");
        if (StringUtils.hasLength(st)) {
            st += ":00";
            qw.ge("item.st", st);
        }

        String et = param.getString("et");
        if (StringUtils.hasLength(et)) {
            et += ":00";
            qw.le("item.et", et);
        }

        String kclxid = param.getString("kclxid");
        if (StringUtils.hasLength(kclxid)) {
            qw.eq("kc.kclxid", kclxid);
        }

        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("kc.jlid", jlid);
        }

        Integer bx = param.getInteger("bx");
        if (null != bx) {
            if (bx == 1) {
                qw.eq("kc.zdrs", bx);
            } else if (bx == 6) {
                qw.gt("kc.zdrs", 1);
                qw.le("kc.zdrs", bx);
            } else if (bx == 7) {
                qw.ge("kc.zdrs", bx);
            }
        }

        String zt = param.getString("zt");
        if (StringUtils.hasLength(zt)) {
            qw.eq("kc.zt", zt);
        }

        String name = param.getString("kcname");
        if (StringUtils.hasLength(name)) {
            qw.and(q -> {
                q.or().like("kc.kcname", name);
                q.or().like("item.itemname", name);
                q.or().like("md.sname", name);
                q.or().like("fj.rname", name);
                q.or().like("jl.jlname", name);
            });
        }

        String jd = param.getString("jd");
        String wd = param.getString("wd");

        AkechengitemMapper itemMapper = (AkechengitemMapper) kechengitemService.getBaseMapper();
        page = itemMapper.getKcitemWithAll(page, qw, jd, wd);
        param.put("kcitems", page);
        return param;
    }

}
